# coding=utf-8

import time
import string


# 处理单个会话的行为，发送消息，进入、离开房间，登录、登出，一些查询等
class ChatSession:

    def __init__(self, sock):
        self.sock = sock
        self.terminator = "\r\n"
        self.data = []
        self.room_name = ""
        self.username = ""
        self.login_time = 0

    # 网络一般用"\r\n"做终止符
    def is_terminator(self, data):
        return data == self.terminator

    # 处理客户端发送的单个字符，仅接受可打印字符与退格
    def collect_data(self, data):
        if data == '\b':
            try:
                self.data.pop()
            except IndexError:
                pass    # 当数据为空，且用户在输入退格，直接忽略即可
        elif data in string.printable:
            self.data.append(data)

    # 当发现终止符时，将之前的数据作为一个整行返回
    def pop_data(self):
        line = "".join(self.data)
        self.data = []
        return line

    # 发送消息
    def send(self, line):
        line = line + self.terminator
        self.sock.send(line)

    # 获取用户名称，用户未登录时返回（地址，端口）
    # ！！不要用该函数判断用户是否登录，用is_login()
    def get_name(self):
        if self.username:
            return self.username
        else:
            return self.sock.getpeername()

    # 判断用户是否登录，不要用get_name()
    def is_login(self):
        return self.username

    # 登录
    def login(self, username):
        self.username = username
        self.login_time = time.time()
        self.send("Login succeed.")

    def online_time(self):
        if self.login_time:
            return time.time() - self.login_time
        else:
            return 0

    # 登出，更新用户在线时长务必在该函数之前
    def logout(self):
        self.username = ""
        self.login_time = 0
        # 客户端关闭可能会发送失败
        try:
            self.send("Logout succeed.")
        except:
            pass

    # 进入房间
    def enter(self, room_name):
        self.room_name = room_name
        self.send("Welcome to room %s." % room_name)

    # 离开房间，返回原房间的名称
    def leave(self):
        old_room_name = self.room_name
        self.room_name = ""
        return old_room_name

    def get_room_name(self):
        return self.room_name

    def is_in_room(self, room_name):
        return room_name == self.room_name

